package org.scboy.dbms.dubbo;

import java.util.List;
import java.util.Map;

import org.apache.dubbo.config.annotation.DubboService;
import org.scboy.coobi.sql.factory.EntityFactory;
import org.scboy.dbms.api.AppManager;
import org.scboy.dbms.dao.BaseSystemConfigDao;
import org.scboy.dbms.service.BaseAppServerService;
import org.scboy.dbms.service.BaseAppService;
import org.scboy.utils.entitys.coobi.Model;
import org.springframework.beans.factory.annotation.Autowired;

import cn.hutool.crypto.digest.MD5;

@DubboService
public class AppManagerImpl implements AppManager{

	@Autowired
	BaseAppService service;
	

	@Autowired
	BaseAppServerService serverService;
	
	@Autowired
	EntityFactory factory;
	
	@Override
	public void register(String ip, int port, String appName,String deploymentPath,String config,String docType) {
		service.register(ip, port, appName, deploymentPath,config,docType);
	}

	@Override
	public void serverReady(String ip, int port, String appName) {
		String serverId=MD5.create().digestHex(appName+"_"+ip+":"+port);
		serverService.update(Model.create().add("id", serverId).add("status", 2));
		
	}

	@Override
	public void serverFailed(String ip, int port, String appName, String exception) {
		String serverId=MD5.create().digestHex(appName+"_"+ip+":"+port);
		serverService.update(Model.create().add("id", serverId).add("status", 0).add("serverMsg", exception));
	}

	@Override
	public void InitSystemConfig(List<Map<String, Object>> configList) {
		BaseSystemConfigDao configDao=factory.getDao(BaseSystemConfigDao.class);
		for (Map<String, Object> map : configList) {
			Model config=Model.convert(map);
			//如果配置不存在，加入到配置管理
			if(configDao.count(Model.create().add("code", config.getString("code")))==0) {
				configDao.insert(config);
			}
		}
	}
}
